package cn.fxl.org.service.impl;

import cn.fxl.basic.service.impl.BasicServiceImpl;
import cn.fxl.org.domain.Department;
import cn.fxl.org.mapper.DepartmentMapper;
import cn.fxl.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DepartmentServiceImpl extends BasicServiceImpl<Department> implements IDepartmentService{
    @Autowired
    private DepartmentMapper departmentMapper;
    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);//先新增获取自增id
        if(department.getParent_id()==null){//如果没选择上级部门
            department.setDirPath("/"+department.getId());//他的上级部门就是自己的id
        }else {
            //如果选择了上级部门,获取上级部门,然后查询,获取上级部门的路径
            String dirPath = departmentMapper.getOne(department.getParent_id()).getDirPath();
            //再拼接自己的id  上级部门路径+自己的id
            department.setDirPath(dirPath+"/"+department.getId());
        }
        //再去修改路径
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //如果部门的上级部门id为null
        if(department.getParent_id()==null){
            //部门路径就为当前部门的/id
            department.setDirPath("/"+department.getId());
        }else {
            //部门的上级部门id不为null
            //先通过上级部门id查询部门,获取上级部门的部门路径
            String dirPath = departmentMapper.getOne(department.getParent_id()).getDirPath();
            //当前部门的部门路径就为上级部门路径+当前部门的部门id
            department.setDirPath(dirPath+"/"+department.getId());
        }
        departmentMapper.update(department);
    }

    @Override
    public List<Department> deptTree() {

        HashMap<Long, Department> map = new HashMap<>();
        List<Department> all = departmentMapper.getAll();
        for (Department department : all) {
            //先把所有的部门对象装进map集合,id为key value为对象
            map.put(department.getId(),department);
        }
        //部门树集合
        ArrayList<Department> deptTree = new ArrayList<>();
        for (Department department : all) {
            //如果部门没有上级部门就是顶级部门,放到部门数集合里
            if(department.getParent_id()==null){
                deptTree.add(department);
            }else {
                //如果有上级部门,就通过上级部门id在map里通过key取出上级部门对象
                Long parent_id = department.getParent_id();
                Department managerDept = map.get(parent_id);
                //再把当前对象存储到上级部门里children
                managerDept.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
